#include<iostream>
#include<cerrno>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<cstdio>
#include<cstring>

void ChildWrite(int child_fd)
{
    char buffer[2048];
    int cnt = 0;
    while(cnt<100)
    {
        snprintf(buffer, sizeof(buffer), "I am child fork. My pid is: %d, My cnt is: %d", getpid(), cnt);
        cnt++;
        sleep(1);
    }

    ssize_t ret = write(child_fd, buffer, strlen(buffer));
}

void FatherRead(int father_fd)
{
    char buffer[2048];
    ssize_t ret = read(father_fd, buffer, sizeof(buffer)-1);

    while(1)
    {
        buffer[ret] = 0;
        std::cout<<"Child say: "<<buffer<<std::endl;
        sleep(1);
    }
}

int main()
{
    //1.父进程创建管道
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if(n < 0)
    {
        std::cerr<<"Pipe fail!"<<std::endl;
    }

    //2.父进程创建子进程
    int rn = fork();

    //子进程部分
    if(rn == 0)
    {
        //子进程向管道里面写入数据
        close(pipefd[0]);
        ChildWrite(pipefd[1]);
    }

    //父进程部分
    //父进程读取管道里面的数据
    close(pipefd[1]);
    FatherRead(pipefd[0]);
    waitpid(rn,nullptr, 0);
    return 0;
}